﻿using Prism.Regions;
using Prism.Regions.Behaviors;
using System;
using System.Collections.Specialized;
using System.Windows;
using Telerik.Windows.Controls;

namespace SmartPlantApp.Common;


public class DockingActivePaneSyncBehavior : RegionBehavior, IHostAwareRegionBehavior
{
    public static readonly string BehaviorKey = "DockingActivePaneSyncBehavior";
    private RadDocking hostControl;
    private bool updatingActiveViewsInDockingActivePaneChanged;


    public DependencyObject HostControl
    {
        get
        {
            return hostControl;
        }

        set
        {
            var newValue = value as RadDocking;
            if (newValue == null && hostControl == null)
            {
                throw new InvalidOperationException("HostControlMustBeARadDocking");
            }

            if (IsAttached)
            {
                throw new InvalidOperationException("RadDockingCannotBeSetAfterAttach");
            }
            hostControl = newValue;
        }
    }

    protected override void OnAttach()
    {
        if (hostControl == null)
        {
            throw new InvalidOperationException("HostControlCannotBeNull");
        }

        hostControl.ActivePaneChanged += OnDockingActivePaneChanged;
        Region.ActiveViews.CollectionChanged += OnActiveViewsCollectionChanged;
    }

    private void OnActiveViewsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (updatingActiveViewsInDockingActivePaneChanged)
        {
            return;
        }

        if (e.Action == NotifyCollectionChangedAction.Add)
        {
            var newActivePane = e.NewItems[0] as RadPane;
            if (newActivePane.IsHidden)
            {
                newActivePane.IsHidden = false;
            }

            hostControl.ActivePane = newActivePane;
        }
    }

    private void OnDockingActivePaneChanged(object sender, Telerik.Windows.Controls.Docking.ActivePangeChangedEventArgs e)
    {
        try
        {
            updatingActiveViewsInDockingActivePaneChanged = true;

            if (e.OriginalSource == sender)
            {
                if (e.OldPane != null)
                {
                    if (Region.Views.Contains(e.OldPane) && Region.ActiveViews.Contains(e.OldPane))
                    {
                        Region.Deactivate(e.OldPane);
                    }
                }

                if (e.NewPane != null)
                {
                    if (Region.Views.Contains(e.NewPane) && !Region.ActiveViews.Contains(e.NewPane))
                    {
                        Region.Activate(e.NewPane);
                    }
                }
            }
        }
        finally
        {
            updatingActiveViewsInDockingActivePaneChanged = false;
        }
    }
}
